package com.example.demo.service;

import com.example.demo.domian.Comment;
import com.example.demo.repository.CommentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ConcurrentModificationException;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class ApiCommentService {
    @Autowired
    private CommentRepository commentRepository;

    @Autowired
    private RedisTemplate redisTemplate;//通过api操纵redis

    //查询
    public Comment findById(Integer id){
        Object o=redisTemplate.opsForValue().get("comment_"+id);//得到缓存
        if(o!=null){
            //缓存中有数据
            return (Comment) o;
        }
        else {
            Optional<Comment> byId=commentRepository.findById(id);
            if(byId.isPresent()){
                Comment comment=byId.get();
                //如果缓存中没有数据，存进缓存中,缓存时间为1 ，天
                redisTemplate.opsForValue().set("comment_"+id,comment,1, TimeUnit.DAYS);
                return  comment;
            }
        }
        return  null;
    }
    //更新

    public  Comment updateComment(Comment comment){
        int i=commentRepository.updateComment(comment.getAuthor(),comment.getId());
        redisTemplate.opsForValue().set("comment_"+comment.getId(),comment);
        return  comment;
    }
    //删除

    public  void deleteComment(Integer id){
        commentRepository.deleteById(id);
        redisTemplate.delete("comment_"+id);
    }
}
